<script setup lang='ts'>
import { ref, reactive, nextTick } from "vue"
import { storeToRefs } from "pinia"
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'

import { totalProductAddPost, totalProductAttachmentPost, totalProductDetailGet, totalProductDeleteAttachmentDel } from "@/api/allProduct"
// 文件上传
import { attachmentUploadApiPost } from "@/api/product.ts"

import { useEnumStore } from "@/store/enumeration"
import useInstance from '@/hooks/useInstance';
import upLoadImgSingle from "@/components/upLoadImgSingle.vue"

const imgUpload1 = ref()

const { allProductType } = storeToRefs(useEnumStore())



defineOptions({
    name: 'addBusiness'
})
const emit = defineEmits(['refresh'])
const { global } = useInstance();
const dialogBasic = ref({
    title: "新建产品大类",
    visible: false,
    width: 700,
    height: 350,
    showFooter: true,
    marginTop: "12vh",
})

const ruleFormRef = ref<FormInstance>()
const ruleImgRef = ref<FormInstance>()
const active = ref(0)
const channelForm = reactive<any>({
    productCategoryName: null, //  产品总称
    productCategoryCode: null, //  产品编码
    productType: null, //  产品类型
    remarks: null, //  remarks
})
const rules = reactive<FormRules>({
    productCategoryName: [
        {
            required: true,
            trigger: 'blur',
            message: "请输入名称"
        },
    ],
    productCategoryCode: [
        {
            required: true,
            trigger: 'blur',
            message: "请输入编码"
        },
    ],
    productType: [
        {
            required: true,
            trigger: 'blur',
            message: "请选择类型"
        },
    ],
})
const ImgForm = reactive<any>({
    one: {
        productCode: null, // 产品编码
        attachmentType: 1, // 附件类型 
        attachmentName: null, // 附件名称
        attachmentAliasName: null, // 附件别名
        attachmentUri: null, // 附件地址
    },

})
const imgRules = reactive({
})
// 图片上传数据 后期删除使用 
const blackSuccess = ref({
    one: null,
    two: null,
    three: null,
    basic: null
})
//显示弹框
const show = (type: string, row?: any) => {
    dialogBasic.value.visible = true
    // resetForm()
    if (type === 'add') {
        dialogBasic.value.title = "产品大类新增"
        dialogBasic.value.height = 600
        global.$resetForm(ruleFormRef.value, channelForm)

    } else {

        dialogBasic.value.height = 600

        global.$resetForm(ruleFormRef.value, channelForm)
        dialogBasic.value.title = "产品大类查看"
        global.$objCopy(channelForm, row)
        // 后期说图片的情况 productproductAttachmentList
        blackSuccess.value.one = row.productAttachmentList?.[0]?.id


        blackSuccess.value.basic = row.id
        // 附件赋值 0 1 2 3 
        
    }
}
const onClose = () => {
    active.value = 0
    dialogBasic.value.visible = false
    resetForm()
    Object.keys(channelForm).forEach(item => channelForm[item] = null)
    Object.keys(ImgForm).map(it => {
        ImgForm[it].productCode = null
        ImgForm[it].attachmentName = null
        ImgForm[it].attachmentAliasName = null
        ImgForm[it].attachmentUri = null
    })
    // imgUpload1.value.clearFile()

}
const onConfirm = async () => {
    active.value++
    return
    /* await ruleFormRef.value?.validate(async isOk => {

        if (isOk) {
            const res = await totalProductAddPost(channelForm)
            if (res.code == 20000) {
                ElMessage({
                    type: "success",
                    message: channelForm.id ? "产品总分类编辑基础数据成功" : "产品总分类新增基础数据成功！"
                })
                active.value++
                setTimeout(async () => {
                    const nowRes = await totalProductDetailGet({ id: res.data })
                    //     // 最新的数据 直接给第一个表单
                    global.$objCopy(channelForm, nowRes.data)
                    blackSuccess.value.basic = res.data
                    ImgForm.one.productCode = nowRes.data.productCode

                }, 300)
            }

        } else {
            ElMessage({
                type: "error",
                message: channelForm.id ? "产品总分类编辑失败 请重试！" : "产品总分类新增失败 请重试！"
            })
        }
    })
 */

}

const resetForm = () => {
    ruleFormRef.value?.resetFields()
}


const nextStep = () => {
    active.value--
}
const file1 = async (file: any) => {
    console.log(file);

    if (file.length) {
        const formData = new FormData()
        formData.append("file", file[0])

        formData.append("param", JSON.stringify({ module: "channelMerchant", type: "1" }))

        const res = await attachmentUploadApiPost(formData)
        if (res.code == 20000) {
            ImgForm.one.attachmentName = res.data.attachmentName
            ImgForm.one.attachmentAliasName = res.data.attachmentAliasName
            ImgForm.one.attachmentUri = res.data.attachmentUri
            imgUpload1.value.newUrl(res.data.attachmentUri, false)
            saveAttachement(1)

        }
    } else {
        ImgForm.one.attachmentName = null
        ImgForm.one.attachmentAliasName = null
        ImgForm.one.attachmentUri = null
        const dele = await totalProductDeleteAttachmentDel({ id: blackSuccess.value.one })
        if (dele.code == 20000) {
            ElMessage({
                type: "success",
                message: "附件图片删除成功"
            })
        }

    }
}

const saveAttachement = async (types: number) => {
    try {
        let res: any = null
        if (types == 1) {
            // 附件上传
            res = await totalProductAttachmentPost(ImgForm.one)
            // 后期删除 数据保存一哈
            blackSuccess.value.one = res.data
        }
        if (res.code == 20000) {
            ElMessage({
                type: "success",
                message: "附件图片上传成功"
            })
        }
    } catch (error) {

    }
}
const onConfirmImg = () => {
    // 这一步如何操作 1 校验 2 
    if (!ImgForm.one.attachmentUri) {
        return ElMessage({
            type: "warning",
            message: "附件图片未上传"
        })
    }

    // 全部上传成功 然后就是 数据回显 数据清楚
    onClose()
    emit('refresh')
    return ElMessage({
        type: "success",
        message: "产品大类新增成功"
    })

}
defineExpose({
    show
})
</script>

<template>
    <SysDialogSlot :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
        :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :draggable="true"
        :margin-top="dialogBasic.marginTop" @on-close="onClose" destroy-on-close @on-confirm="onConfirm">
        <template v-slot:content>
            <div style="margin: 10px 0px;">
                <el-steps :active="active" finish-status="success" align-center>
                    <el-step title="产品大类基础信息" />
                    <el-step title="产品大类附件上传" />
                    <!-- <el-step title="创建完成" /> -->
                </el-steps>
            </div>
            <el-form ref="ruleFormRef" :model="channelForm" :rules="rules" label-width="150px" class="demo-ruleForm"
                status-icon v-show="active === 0">
                <el-form-item label="类型" prop="productType">
                    <BlackSelect v-model:select-value="channelForm.productType" :options="allProductType" disabled>
                    </BlackSelect>
                </el-form-item>

                <el-form-item label="名称" prop="productCategoryName">
                    <el-input v-model="channelForm.productCategoryName" maxlength="128" clearable disabled
                        show-word-limit placeholder="请输入" />
                </el-form-item>
                <el-form-item label="编码" prop="productCategoryCode">
                    <el-input v-model="channelForm.productCategoryCode" placeholder="请输入" clearable disabled />
                </el-form-item>
             
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="channelForm.remarks" placeholder="请输入" maxlength="256" clearable disabled
                        show-word-limit />
                </el-form-item>
            </el-form>


            <el-form ref="ruleImgRef" :model="ImgForm" style="margin-top: 50px;" label-width="200px"
                class="demo-ruleForm" status-icon v-show="active === 1">
                <el-form-item label="附件图片">
                    <el-image style="width: 100px; height: 100px"
                    :preview-src-list="[channelForm.productAttachmentList?.[0]?.attachmentUri]" :src="channelForm.productAttachmentList?.[0]?.attachmentUri" fit="fill"></el-image>
                </el-form-item>
            </el-form>

        </template>

        <template v-slot:myFooter>
            <div class="dialog-footer">
                <el-button @click="onClose">取消</el-button>
                <el-button @click="nextStep" v-if="active !== 0">上一步</el-button>
                <el-button type="success" @click="onConfirm" v-if="active === 0">下一步</el-button>
                <!-- <el-button type="success" @click="onConfirmImg" v-if="active === 1">确定</el-button> -->
            </div>
        </template>

    </SysDialogSlot>
</template>

<style lang='scss' scoped>
.my-header {
    height: 48px;
    font-size: 18px;
}
</style>
